package org.mashart.pink.m.gps.data;

import java.util.Enumeration;
import java.util.Vector;

/**
 * Helper for GPS data parsing implementation
 *
 * Provides useful <code>split()</code> but <code>Talker</code> implementations
 * shouldn't necessary extend from this abstract class
 */
public abstract class AbstractParser implements Talker {

    /**
     * Splits given string <code>str</code> into an array of
     * strings.
     * <code>sep</code> - string fields separator. NMEA sentences
     * use ","
     *
     * @return empty array of <code>str</code> is NULL;
     * @return original <code>str</code> if <code>sep</code> is NULL or
     * empty;
     * @return array of strings otherwise.
     */
    public final String[] split(String str, String sep) {
        if (str == null) return new String[0];
        if (sep == null || sep.length() == 0)
            return new String[]{str};

        Vector strings = new Vector(15); // 15 elements in $GPGGA
        int sep_len = sep.length();
        int marker = 0;
        int index = str.indexOf(sep);
        while (index > 0) {
            strings.addElement(str.substring(marker, index));
            marker = index + sep_len;
            index = str.indexOf(sep, marker);
        }
        // adding the last element
        strings.addElement(str.substring(marker));

        String[] splitted = new String[strings.size()];
        Enumeration e = strings.elements();
        index = 0;
        while (e.hasMoreElements()) {
            splitted[index] = (String)e.nextElement();
            index++;
        }

        return splitted;
    }
}
